<template>
  <view class="container">
    <!-- 订单状态 -->
    <view class="status-card">
      <view class="status">{{ getStatusText(orderInfo) }}</view>
    </view>

    <!-- 收货地址 -->
    <view class="address-card">
      <view class="info">
        <view class="user">
          <text class="name">{{ orderInfo.address?.name }}</text>
          <text class="phone">{{ orderInfo.address?.phone }}</text>
        </view>
        <view class="address">
          {{ orderInfo.address?.province }}{{ orderInfo.address?.city
          }}{{ orderInfo.address?.district }}{{ orderInfo.address?.detail }}
        </view>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-card">
      <view
        class="goods-item"
        v-for="(item, index) in orderInfo.goods"
        :key="index"
      >
        <image :src="item.image" mode="aspectFill" class="goods-img"></image>
        <view class="goods-info">
          <view class="title">{{ item.title }}</view>
          <view class="price-info">
            <text class="price">￥{{ item.price }}</text>
            <view class="count-info">
              <text>下单 {{ item.count }} 件</text>
              <text v-if="item.giftNum > 0" class="gift"
                >赠送 {{ item.giftNum }} 件</text
              >
              <text class="total">共 {{ item.count + item.giftNum }} 件</text>
            </view>
          </view>
          <view class="amount">
            <text>小计：</text>
            <text class="price"
              >￥{{ (item.price * item.count).toFixed(2) }}</text
            >
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-card">
      <view class="order-info">
        <view class="item">
          <text>订单编号</text>
          <text>{{ orderInfo.orderNo }}</text>
        </view>
        <view class="item">
          <text>下单时间</text>
          <text>{{ orderInfo.createTime }}</text>
        </view>
        <view class="item" v-if="orderInfo.status === 2">
          <text>完成时间</text>
          <text>{{ orderInfo.completeTime }}</text>
        </view>
        <view class="item" v-if="orderInfo.deliveryConfirmedAt">
          <text>送货确认时间</text>
          <text>{{orderInfo.deliveryConfirmedAt }}</text>
        </view>
        <view class="item" v-if="orderInfo.deliveryPerson">
          <text>送货人</text>
          <text>{{ orderInfo.deliveryPerson }}</text>
        </view>
        <view class="item" v-if="orderInfo.customerConfirmedAt">
          <text>确认收货时间</text>
          <text>{{ orderInfo.customerConfirmedAt }}</text>
        </view>
        <view class="item" v-if="orderInfo.customer">
          <text>确认收货人</text>
          <text>{{ orderInfo.customer }}</text>
        </view>
      </view>
      <view class="amount-info">
        <view class="total">
          <text>订单总额</text>
          <text class="amount">￥{{ orderInfo.totalAmount }}</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="footer" v-if="showFooter">
      <template v-if="orderInfo.status === 1">
        <button 
          class="cancel-btn" 
          @click="cancelOrder" 
          v-if="!orderInfo.customerConfirmedAt && !orderInfo.deliveryConfirmedAt"
        >
          取消订单
        </button>
        
        <button 
          class="confirm-btn" 
          @click="confirmReceive" 
          v-if="isAdmin && !orderInfo.deliveryConfirmedAt"
        >
          确认送货
        </button>
        
        <button 
          class="confirm-btn" 
          @click="confirmReceive" 
          v-if="!isAdmin && orderInfo.deliveryConfirmedAt && !orderInfo.customerConfirmedAt"
        >
          确认收货
        </button>
      </template>
      
      <template v-else-if="orderInfo.status === 3">
        <button class="recover-btn" @click="recoverOrder">恢复订单</button>
      </template>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { config } from "@/utils/config.js";

const orderInfo = ref({});
const isAdmin = computed(() => uni.getStorageSync("userRole") === 2);

// 控制底部操作栏的显示
const showFooter = computed(() => {
  if (orderInfo.value.status === 3) return true;
  if (orderInfo.value.status === 1) {
    if (isAdmin.value) {
      return !orderInfo.value.deliveryConfirmedAt;
    } else {
      return !orderInfo.value.customerConfirmedAt;
    }
  }
  return false;
});

// 获取订单详情
const getOrderDetail = async (id) => {
  try {
    const res = await uni.request({
      url: config.baseUrl + `/api/orders/${id}`,
      method: "GET",
      header: {
        Authorization: `Bearer ${uni.getStorageSync("token")}`,
      },
    });

    if (res.data.code === 200) {
      const data = res.data.data;
      orderInfo.value = {
        ...data,
        goods: data.orderGoods.map((item) => ({
          id: item.goodsId,
          title: item.goodsTitle,
          price: item.goodsPrice,
          count: item.num,
          giftNum: item.giftNum,
          giftRuleText: item.giftRuleText,
          image: item.goodsImage
            ? `${config.imageBaseUrl}${item.goodsImage}`
            : "/static/images/default-goods.png",
        })),
        totalAmount: data.total_price,
        statusText: getStatusText(data.status),
        createTime: formatTime(data.createdAt),
        completeTime:
          data.updatedAt && data.status === 2 ? formatTime(data.updatedAt) : "",
      };
    } else {
      throw new Error(res.data.message || "获取订单详情失败");
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
    uni.showToast({
      title: error.message || "获取订单详情失败",
      icon: "none",
    });
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return "";
  const date = new Date(timeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hour = String(date.getHours()).padStart(2, "0");
  const minute = String(date.getMinutes()).padStart(2, "0");
  const second = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 确认收货
const confirmReceive = async () => {
  // 检查是否可以确认
  if (isAdmin.value && orderInfo.value.deliveryConfirmedAt) {
    uni.showToast({
      title: '已确认送货',
      icon: 'none'
    });
    return;
  }
  
  if (!isAdmin.value && orderInfo.value.customerConfirmedAt) {
    uni.showToast({
      title: '已确认收货',
      icon: 'none'
    });
    return;
  }

  const confirmText = isAdmin.value ? '确认已送达商品？' : '确认已收到商品？';
  
  uni.showModal({
    title: "提示",
    content: confirmText,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await uni.request({
            url: config.baseUrl + `/api/orders/${orderInfo.value.id}/confirm`,
            method: "POST",
            header: {
              Authorization: `Bearer ${uni.getStorageSync("token")}`,
              "Content-Type": "application/json",
            },
            data: {
              role: isAdmin.value ? 2 : 1,
            },
          });

          if (result.data.code === 200) {
            uni.showToast({
              title: isAdmin.value ? "已确认送货" : "已确认收货",
              icon: "success",
              success: () => {
                setTimeout(() => {
                  uni.$emit('orderListUpdate')
                  uni.navigateBack()
                }, 1500)
              },
            });
          } else {
            throw new Error(result.data.message);
          }
        } catch (error) {
          uni.showToast({
            title: error.message || "操作失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 取消订单
const cancelOrder = async () => {
  uni.showModal({
    title: "提示",
    content: "确认取消订单？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await uni.request({
            url: config.baseUrl + `/api/orders/${orderInfo.value.id}/cancel`,
            method: "POST",
            header: {
              Authorization: `Bearer ${uni.getStorageSync("token")}`,
            },
          });

          if (result.data.code === 200) {
            uni.showToast({
              title: "订单已取消",
              icon: "success",
              success: () => {
                setTimeout(() => {
                  uni.$emit('orderListUpdate')
                  uni.navigateBack()
                }, 1500)
              },
            });
          } else {
            throw new Error(result.data.message);
          }
        } catch (error) {
          uni.showToast({
            title: error.message || "操作失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 恢复订单
const recoverOrder = async () => {
  uni.showModal({
    title: "提示",
    content: "确认恢复该订单？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await uni.request({
            url: config.baseUrl + `/api/orders/${orderInfo.value.id}/restore`,
            method: "POST",
            header: {
              Authorization: `Bearer ${uni.getStorageSync("token")}`,
            },
          });

          if (result.data.code === 200) {
            uni.showToast({
              title: "订单已恢复",
              icon: "success",
              success: () => {
                setTimeout(() => {
                  uni.$emit('orderListUpdate')
                  uni.navigateBack()
                }, 1500)
              },
            });
          } else {
            throw new Error(result.data.message);
          }
        } catch (error) {
          uni.showToast({
            title: error.message || "操作失败",
            icon: "none",
          });
        }
      }
    },
  });
};

// 获取状态文本
const getStatusText = (order) => {
	if (isAdmin.value) {
    if (order.status === 1) {
      if (order.customerStatus) {
        return "客户已确认";
      }
      if (order.deliveryStatus) {
        return "已确认";
      }
	  return '待送货'
    }else if(order.status === 2){
      return '已完成'
    }else if(order.status === 3){
      return '已取消'
    }
  } else {
    if(order.status === 1){
		if (order.customerStatus) {
        return "我已确认";
      }
      if (order.deliveryStatus) {
        return "送货员已确认";
      }
	  else{
		return '待收货'
	  }
    }else if(order.status === 2){
      return '已完成'
    }else if(order.status === 3){
      return '已取消'
    }
  }
};

onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const orderId = currentPage.options.id;

  if (orderId) {
    getOrderDetail(orderId);
  }
});
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 120rpx;
}

.status-card {
  background: #ff6b81;
  padding: 40rpx 30rpx;

  .status {
    font-size: 36rpx;
    color: #fff;
    font-weight: bold;
  }
}

.address-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;

  .info {
    .user {
      margin-bottom: 16rpx;

      .name {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
        margin-right: 20rpx;
      }

      .phone {
        font-size: 28rpx;
        color: #666;
      }
    }

    .address {
      font-size: 26rpx;
      color: #666;
      line-height: 1.4;
    }
  }
}

.goods-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;

  .goods-item {
    display: flex;
    margin-bottom: 30rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .goods-img {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }

    .goods-info {
      flex: 1;
      margin-left: 20rpx;

      .title {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 16rpx;
      }

      .price-info {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16rpx;

        .price {
          font-size: 32rpx;
          color: #ff6b81;
          font-weight: bold;
        }

        .count-info {
          text-align: right;

          text {
            display: block;
            font-size: 24rpx;
            color: #666;
            line-height: 1.6;

            &.gift {
              color: #ff6b81;
            }

            &.total {
              color: #333;
              font-weight: bold;
            }
          }
        }
      }

      .amount {
        display: flex;
        justify-content: flex-end;
        align-items: center;

        text {
          font-size: 24rpx;
          color: #666;

          &.price {
            font-size: 28rpx;
            color: #ff6b81;
            font-weight: bold;
          }
        }
      }
    }
  }
}

.order-card {
  background: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 30rpx;

  .order-info {
    .item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16rpx;

      text {
        font-size: 26rpx;
        color: #666;

        &:last-child {
          color: #333;
        }
      }
    }
  }

  .amount-info {
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #f5f5f5;

    .total {
      display: flex;
      justify-content: space-between;
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1rpx solid #f5f5f5;

      text {
        font-size: 28rpx;
        color: #333;
        font-weight: bold;

        &.amount {
          color: #ff6b81;
          font-size: 36rpx;
        }
      }
    }
  }
}

.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;

  button {
    min-width: 180rpx;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0;
    margin-left: 20rpx;

    &.cancel-btn {
      background: #fff;
      color: #666;
      border: 1rpx solid #ddd;
    }

    &.confirm-btn {
      background: #ff6b81;
      color: #fff;
    }

    &.recover-btn {
      background: #4cd964;
      color: #fff;

      &:active {
        background: darken(#4cd964, 5%);
      }
    }
  }
}
</style>
